package com.ruoyi.wechat.config;

import com.ruoyi.wechat.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 延时订单队列
 * </p>
 *
 * @author YinHeng
 * @since 2024/4/9
 */
@Component
public class OrderDelayQueue {

    private final DelayQueue<DelayedOrder> delayQueue = new DelayQueue<>();


    public void addOrderToQueue(DelayedOrder order) {
        delayQueue.put(order);
        System.out.println("订单 " + order.getTradeNo() + "在 " + LocalDateTime.now() + " 添加到延迟队列");
    }

    // 启动订单处理线程池
    private ExecutorService executorService = Executors.newFixedThreadPool(10);

    @PostConstruct
    public void init() {
        executorService.execute(this::processOrders);
    }

    private void processOrders() {
        while (true) {
            try {
                DelayedOrder order = delayQueue.take(); // 从延迟队列中取出已经过期的订单
                System.out.println("订单 " + order.getTradeNo() + "在 " + LocalDateTime.now() + " 取消");
                order.cancelOrder();
                // 在这里执行取消订单的逻辑，比如更新数据库状态等
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
